<template>
  <div>
    <el-menu
        :default-active="currentPath"
        router
        mode="horizontal"
        background-color="white"
        text-color="#222"
        active-text-color="#409EFF"
        style="min-width: 1300px">
      <el-menu-item v-for="(item,i) in navList" :key="i" :index="item.name">
        {{ item.navItem }}
      </el-menu-item>
      <span class="navMenu-title">Link-With-Heath 在线问诊系统</span>
      <!--<el-input-->
      <!--    placeholder="快速搜索..."-->
      <!--    prefix-icon="el-icon-search"-->
      <!--    size="medium"-->
      <!--    style="width: 300px;position:absolute;margin-top: 12px;right: 18%"-->
      <!--    v-model="keywords">-->
      <!--</el-input>-->
      <el-dropdown class="notification-icon">
      <el-badge :value="notRead"
                type="primary">
        <el-button
            icon="el-icon-message-solid"
            size="small"
            circle>
        </el-button>
      </el-badge>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-for="item in infoList"
                            @click="isRead(item.id)">
            <span>{{item.infoName}}</span>
            {{item.content}}
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>

      <!--下拉组件-->
      <el-submenu style="position:absolute;right: 0%" index="1">
        <template slot="title">
            <span class="el-dropdown-link">
               我的信息
            </span>
        </template>

          <el-menu-item v-for="item in subMenu()">
            {{item}}
          </el-menu-item>
          <el-menu-item v-if="showChangeBtn"
                        @click="showDoctorStatus = true">
            切换状态
          </el-menu-item>

          <el-menu-item @click.native="logout">退出</el-menu-item>


      </el-submenu>
      <!--/下拉组件-->
    </el-menu>

    <el-dialog
        title="设置状态"
        :visible.sync="showDoctorStatus"
        width="30%">
      <el-form>
        <el-form-item>
          <el-radio-group v-model="doctorMessage.doctorStatus">
            <el-radio :label="1">出诊</el-radio>
            <el-radio :label="4">在线</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button @click="showDoctorStatus = false">取 消</el-button>
          <el-button type="primary" @click="changeStatus">确 定</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "NavMenu",
  data () {
    return {
      showDoctorStatus: false,

      userMessage:{
        userId: 0,
        username: '',
        telephone: '',
        email: '',
        isDoctor: false,
        userStatus: 0,
        statusName: '',
        gender: 0,
        ipLock: '',
      },

      doctorMessage: {
        drId: 0,
        hospitalId: 0,
        departmentId: 0,
        realName: '',
        title: 0,
        perInfo: '',
        doctorStatus: 0,
        userId: 0,
        hospitalName: '',
        titleName: '',
        statusName: '',
        departmentName: ''
      },


      navList: [
        {name: '/index', navItem: '首页'},
        {name: '/doctorInfo', navItem: '医生信息'},
        {name: '/inquiryHistory', navItem: '会诊历史'},
        {name: '/userInfo', navItem: '个人中心'}
      ],

      wsConfig: {
        wsUrl: 'ws://localhost:8808',
        server: null,
        isConnected: false,
      },

      info: {
        id: 0,
        sender: 0,
        receiver: 0,
        content: '',
        infoType: 0,
        createTime: 0,
        isRead: false,
        infoName: ''
      },
      infoList: [],
      notRead: 0
    }
  },
  created() {
    this.getUserInfo();
  },
  computed: {
    hoverBackground () {
      return '#ffd04b'
    },
    currentPath () {
      var x = this.$route.path.indexOf('/', 1)
      if (x !== -1) {
        return this.$route.path.substring(0, x)
      } else {
        return this.$route.path
      }
    },
    userInfoList(){
      const userInfo = this.userMessage;
      let userShow = {
          'userId': userInfo.userId,
          'username': userInfo.username,
          'Status': userInfo.Status,
          }

      return userInfo;
    },
    showChangeBtn(){
      return this.canChange();
    }
  },methods: {
    getUserInfo(){
      const self = this;
      this.$axios.get('api/user/accessUser')
          .then(res => {
            self.userMessage = res.data.data;

            let userId = self.userMessage.userId;
            //连接notificationServer
            self.initWebsocket('/notification/'+userId)


            //如果认证为医生，再获取医生信息
            if(self.userMessage.isDoctor){
              self.$axios.get('api/doctor/accessDoctorInfo')
                  .then(res => {
                    self.doctorMessage = res.data.data;
                  })
                  .catch(err => {
                    console.log(err);
              })
            }
            //获取用户未读消息
            self.getNotReadInfo()

          }).catch(err => {
            console.log(err)
            self.$router.push("/login");
          })

    },
    logout(){
      this.$axios.get("api/unLogin/logout",null).then(res => {
        console.log(res.data.data)
        localStorage.clear()
        sessionStorage.clear()
        this.$store.commit("resetState")
        this.$router.push("/login")
      })
    },
    subMenu(){
      const self = this;
      let menu = {
        account: '用户id '+self.userMessage.userId,
        username: '用户名 '+self.userMessage.username,
        userStatus: '状态 '+self.userMessage.statusName
      }

      let doctor = {
        account: '用户id ' + self.userMessage.userId,
        doctorId: '医生id ' + self.doctorMessage.drId,
        doctorName: '姓名 ' + self.doctorMessage.realName,
        department: '科室 ' + self.doctorMessage.departmentName,
        drTitle: '职称 ' + self.doctorMessage.titleName,
        hospitalName: '所属单位 ' + self.doctorMessage.hospitalName
      }
      return self.userMessage.isDoctor ? doctor : menu;

    },
    changeStatus(){
      const self = this;
      let json = {
        'doctorId': self.doctorMessage.drId,
        'doctorStatus': self.doctorMessage.doctorStatus
      }

      this.$axios.post('api/doctor/statusSetting', json)
          .then(res=>{
            self.doctorMessage = res.data.data;
          })

       self.showDoctorStatus = false
    },

    getNotReadInfo(){
      const self = this;
      let json = {'isRead': 'notRead'};
      self.$axios.post('api/sysInfo/receiveUserSysInfo',json)
          .then(res => {
            self.infoList = res.data.data;
            self.notRead = self.infoList.length;
          }).catch(err => {
            //TODO
          })
    },
    isRead(val){
      const self = this;
      let json = {
        'sysInfoId': Number(val)
      }

      this.$axios.post('api/sysInfo/readSysInfo',json)
          .then(res=>{
            self.getNotReadInfo();
          })
    },

    canChange(){
      const self = this;
      if(self.userMessage.isDoctor){

        //TODO 这里检测有误 医生状态为初始的零，没有通过函数更新

        let num = self.doctorMessage.doctorStatus;

        //出诊 在线 下线
        if(num === 1 || num === 4 || num === 5)
          return true;
        console.log(num);
      }

      return false;
    },

    //------------------------------------------------------------//
    initWebsocket(api){
      const self = this;

      const url = self.wsConfig.wsUrl + api;
      self.wsConfig.server = new WebSocket(url);
      self.wsConfig.server.onmessage = self.nsOnMessage;
      self.wsConfig.server.onclose = self.nsOnClose;
      self.wsConfig.server.error = self.nsOnError;
      self.wsConfig.server.onclose = self.nsOnClose;
      self.wsConfig.server.onopen = self.nsOnOpen;

    },

    nsOnOpen(){
      const self = this;
      self.wsConfig.isConnected = true;
      console.log("开启websocket")
      self.$notify({
        title: '通知',
        message: '已连接',
        type: 'success'
      })
    },

    nsOnError(e){
      //Element.Message.error("");
      console.log(e)
    },

    nsOnMessage(e){
      const self = this;
      const res = JSON.parse(e.data);
      self.$notify({
        title: res.infoName,
        message: res.content,
        type: 'success'
      });
      //更新未读消息
      self.getNotReadInfo()
    },
    nsSend(Data){
      const self = this;
      let jsonData = JSON.stringify(Data);
      self.wsConfig.server.send(Data);
    },
    nsOnClose(e){
      console.log('server close!',e)
    }


  }
}

</script>

<style scoped>
  a{
    text-decoration: none;
  }
  span {
    pointer-events: none;
  }
  .navMenu-title {
    position: absolute;
    padding-top: 20px;
    right: 40%;
    font-size: 20px;
    font-weight: bold
  }

  .el-dropdown-link {
    cursor: pointer;
  }
  .notification-icon{
    position:absolute;
    right: 10%;
    margin-top: 15px;
  }

</style>